<?php

/**
 * Allows access to MySQL through Store procedure calls
 * It allows set parameters with its types and generates a sentence
 * to call a SP with the included parameters
 * 
 * @author ntourne
 * @date 27/08/2011
 */

require_once(HOME_PATH.'class/class.DBParameter.php');

class DBUtil {

	var $parameters = array();
	var $name;

	
	function setParameter($pName, $pType) {
		$param = new DBParameter();
		$param->name = $pName;
		$param->type = $pType;
		$count = count($this->parameters);		
		$this->parameters[$count + 1] = $param;
	}

	
	function setSPName($pName) {
		$this->name = $pName;
	}
	

	function handleParam($pParam) {
		$param = $pParam->name;
		switch ($pParam->type) {
			case "INT":
				$param = $param;
				break;
			case "VARCHAR":
				$param = "'" . $param . "'";
				break;
			case "DATETIME":
				$param = "'" . $param . "'";
				break;
			case "TEXT":
				$param = "'" . $param . "'";
				break;
			case "DATE":
				$param = "'" . $param . "'";
				break;
			case "CHAR":
				$param = "'" . $param . "'";
				break;				
		}
		return $param;
	}

	
	function generateSP() {
		$count = count($this->parameters);
		$string = "CALL";
		if ($count > 0) {
			$string = $string . " " . $this->name . "(";
			for($i = 1; $i <= $count; $i++) {
				$string = $string . $this->handleParam($this->parameters[$i]);
				if ($i != $count)
					$string = $string . ", ";
			}
			$string = $string . ")";
		}
		else
			$string = $string . " " . $this->name;
		return $string;
	}

}

?>